package edu.jit.flowers.utils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.print.DocFlavor.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = -2231254113063403107L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		Class<?> clazz = this.getClass();
		try {
			Method me = clazz.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
			String uri = (String)me.invoke(this, req,resp);
			if(uri.startsWith("r")) {
				uri = uri.substring(uri.indexOf(":")+1);
				uri = getServletContext().getContextPath()+"/"+uri;
				resp.sendRedirect(uri);
//				System.out.println(uri);
			} else {
				uri = uri.substring(uri.indexOf(":")+1);
				uri = "/"+uri;
				req.getRequestDispatcher(uri).forward(req,resp);
			}
		} catch (NoSuchMethodException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
